package com.ofhb.webapp.client.ui.navbar;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.ofhb.webapp.client.ui.navbar.events.NavChangeEvent;
import com.ofhb.webapp.client.ui.navbar.events.NavChangeEventHandler;
import com.ofhb.webapp.client.utils.EventUtil;

public class NavigationBar extends HorizontalPanel{
	
	private int selectedIndex = 0;
	private List<String> listNavLabels = null;
	private HorizontalPanel horizontalPanel = null;
	
	public NavigationBar() {
		
		setWidth("1000px");
		setStyleName("app-nav-bar");
		
		horizontalPanel = new HorizontalPanel();
		horizontalPanel.setWidth("");
		
		add(horizontalPanel);
	}

	private List<String> getListNavLabels() {
		if(listNavLabels == null) {
			listNavLabels = new ArrayList<String>();
		}
		return listNavLabels;
	}

	public void addNavItem(String navCaption) {
		getListNavLabels().add(navCaption);
	}
	
	public void draw() {
		
		for(String caption: listNavLabels) {
			Label lblNavItem = new Label(caption);
			lblNavItem.setWordWrap(false);
			lblNavItem.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
			lblNavItem.setStyleName("app-nav-bar-lbl");
			
			attachClickHandler(lblNavItem);
			
			horizontalPanel.add(lblNavItem);
		}
	}
	
	private void attachClickHandler(Label lblNavItem) {
		ClickHandler clickHandler = new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				
				int count = horizontalPanel.getWidgetCount();
				for(int i=0; i<count; i++) {
					horizontalPanel.getWidget(i).setStyleName("app-nav-bar-lbl");	
				}
				
				Label lbl = (Label) event.getSource();
				selectedIndex = horizontalPanel.getWidgetIndex(lbl);
				lbl.setStyleName("app-nav-bar-sel");
				
				EventUtil.EVENT_BUS.fireEvent(new NavChangeEvent(selectedIndex));
			}
		};
		lblNavItem.addClickHandler(clickHandler);
	}
	
	public void setSelectedIndex(int index) {
		Label lbl = (Label) horizontalPanel.getWidget(index);
		selectedIndex = index;
		lbl.setStyleName("app-nav-bar-sel");
	}
	
	public void addAttachHandler(NavChangeEventHandler handler) {
		EventUtil.EVENT_BUS.addHandler(NavChangeEvent.TYPE, handler);
	}
}
